package cn.grayrelese;

import cn.grayrelese.response.CustomResponse;
import com.alibaba.fastjson.JSONObject;
import com.netflix.hystrix.contrib.javanica.annotation.HystrixCommand;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.client.circuitbreaker.EnableCircuitBreaker;
import org.springframework.cloud.netflix.ribbon.RibbonClient;
import org.springframework.core.env.Environment;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

import javax.annotation.Resource;

import static cn.grayrelese.response.CustomResponse.responseMessages;

@RibbonClient(name="provider-service")
//允许断路器 熔断器会导致RequestContextHolder.getRequestAttributes()为空.解决方法:自定义熔断策略
@EnableCircuitBreaker
@SpringBootApplication
@RestController
public class ConsumerVersion2Application {

    @Autowired
    private RestTemplate restTemplate;
    @Resource
    Environment env;
//    private static final Logger logger = LoggerFactory.getLogger(ConsumerVersion2Application.class);

    public static void main(String[] args) {
        SpringApplication.run(ConsumerVersion2Application.class, args);
    }

    //请求熔断注解，当服务出现问题时候会执行fallbackMetho属性的名为helloFallBack的方法
    @HystrixCommand(fallbackMethod = "responseFallBack")
    @RequestMapping(value = "/test")
    public String test() {
        return restTemplate.getForObject("http://provider-service/provider-test", String.class);
    }

     /**
     * 熔断器回滚
     * @param throwable
     * @return
     */
    public String responseFallBack(Throwable throwable){
        return JSONObject.toJSONString
                (responseMessages(env,String.format("服务异常！异常信息如下：%s",throwable.getMessage())));
    }
}